import os
import logging
import threading
import asyncio
from logging import Formatter
from logging.handlers import RotatingFileHandler

class LoggerManager:
    """日志管理器 - 封装所有日志相关功能的单例类"""
    _instance = None
    _initialized = False
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(LoggerManager, cls).__new__(cls)
        return cls._instance
    
    def __init__(self):
        # 确保只初始化一次
        if not LoggerManager._initialized:
            self.root_logger = logging.getLogger()
            self.file_handler = None
            self.stream_handler = None
            self.formatter = None
            LoggerManager._initialized = True
    
    class ContextFormatter(Formatter):
        """自定义格式：包含线程ID和协程ID"""
        def format(self, record):
            # 线程ID
            record.thread_id = threading.get_ident()
            # 协程ID（仅在协程中有效）
            try:
                record.coroutine_id = id(asyncio.current_task())
            except RuntimeError:
                record.coroutine_id = -1  # 非协程环境
            return super().format(record)
    
    def _ensure_log_directory(self):
        """确保日志目录存在"""
        log_dir = "logs"
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
    
    def setup_logging(self):
        """初始化日志配置"""
        # 确保日志目录存在
        self._ensure_log_directory()
        
        # 检查是否已经配置了根日志器
        if self.root_logger.handlers:
            # 如果已经配置过，就不再重复配置
            return
        
        # 创建格式化器
        self.formatter = self.ContextFormatter(
            '%(asctime)s - th=%(thread_id)s - co=%(coroutine_id)s - [%(levelname)s] - [%(name)s]: %(message)s'
        )

        # 创建日志处理器
        self.file_handler = RotatingFileHandler(
            "logs/app.log", 
            maxBytes=10*1024*1024,  # 10MB, 避免单个日志文件过大
            backupCount=5, 
            encoding='utf-8'
        )
        self.stream_handler = logging.StreamHandler()
        
        # 为处理器设置格式器
        self.file_handler.setFormatter(self.formatter)
        self.stream_handler.setFormatter(self.formatter)
        
        # 配置根日志器
        self.root_logger.setLevel(logging.INFO)
        self.root_logger.addHandler(self.file_handler)
        self.root_logger.addHandler(self.stream_handler)
    
    def shutdown_logging(self):
        """关闭所有日志处理器"""
        for handler in self.root_logger.handlers[:]:
            handler.close()
            self.root_logger.removeHandler(handler)
        self.file_handler = None
        self.stream_handler = None
        
    def get_logger(self, name=None):
        """获取指定名称的日志器，如果未指定则获取根日志器"""
        return logging.getLogger(name)

# 创建全局单例实例
logger_manager = LoggerManager()

# 保持向后兼容性的函数别名
def setup_logging():
    logger_manager.setup_logging()


def shutdown_logging():
    logger_manager.shutdown_logging()